/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.rolgps.libns.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.rolgps.libnstack.parser.ParserFactory;
import org.rolgps.libnstack.protocol.Message;
import org.rolgps.libnstack.protocol.MessageParser;

/**
 *
 * @author xeph
 */
public class SocketListener implements Runnable{

    private Socket inputSocket = null;
    private boolean doNotExitUntilThisBecomesFalse = true;
    private BufferedReader input = null;
    private MessageParser parser = ParserFactory.getDefaultParser();
    private BlockingQueue<Message> messageQueue = null;

    public SocketListener(Socket s, BlockingQueue<Message> q) {
        this.inputSocket = s;
        this.messageQueue = q;
    }

    public void shutdown(){
        doNotExitUntilThisBecomesFalse = false;
    }
    @SuppressWarnings("unchecked")
    public void run() {
        try {
            input = new BufferedReader(new InputStreamReader(inputSocket.getInputStream()));
            while (input != null && doNotExitUntilThisBecomesFalse) {
                Message message = parser.parseString(input);
                assert message != null;
                messageQueue.put(message);
            }
//            input.close();
        } catch (InterruptedException ex) {
            Logger.getLogger(SocketListener.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SocketListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
